/* =================================================
 * Package:			dk.iha.toksEditor
 * File:			MaxToksDBAdapter.java
 * Description:		This is the class for which
 * 					is responsible for showing which
 * 					patients TOKS is not finished.
 * 
 * Responsible
 * =================================================
 * Name:			Vinnie Juul
 * Study number:	09767
 */
package dk.iha.toksEditor;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MaxToksDBAdapter
{
	private static final String DATABASE_NAME = "maxToksEditor.db";
	private static final String DATABASE_TABLE = "MaxToks";
	private static final int DATABASE_VERSION = 1;
	private SQLiteDatabase db;
	private final Context context;
	private DBOpenHelper dbHelper;
	
	//Column names
	public static final String KEY_ID = "_id";
	public static final String KEY_PATIENT_CPR = "patientCPR";
	public static final String KEY_MAX_TOKS = "maxToks";
	
	public MaxToksDBAdapter(Context _context) 
	{
		this.context = _context;
		dbHelper = new DBOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
	}
	
	/**
	 * Closes the connection to the database.
	 */
	public void close() 
	{
		db.close();
	}
	
	/**
	 * Open the connection to the database.
	 * @throws SQLiteException If it can't open a writable database connection it will try to open a readable connection.
	 */
	public void open() throws SQLiteException 
	{
		try 
		{
			db = dbHelper.getWritableDatabase();
		} 
		
		catch (SQLiteException ex) 
		{
			db = dbHelper.getReadableDatabase();
		}
	}
	
	/**
	 * Open the connection to the database in read only mode.
	 * @throws SQLiteException If it can't open a database connection.
	 */
	public void openReadOnly() throws SQLiteException 
	{
		try 
		{
			db = dbHelper.getReadableDatabase();
		} 
		
		catch (SQLiteException ex) 
		{
			
		}
	}
	
	/**
	 * Insert a new max Toks in the database
	 * @param cpr number for the patient
	 * @param Toks the new max toks value
	 * @return The row ID of the newly inserted row, or -1 if an error occurred. 
	 */
	public long insertMaxTosk(String cpr, Integer Toks) 
	{
		// Create a new row of values to insert.
		ContentValues newValues = new ContentValues();
		
		// Assign values for each row.
		newValues.put(KEY_PATIENT_CPR, cpr);
		newValues.put(KEY_MAX_TOKS, Toks);
		
		// Insert the row.
		return db.insert(DATABASE_TABLE, null, newValues);
	}
	
	/**
	 * Get a specific patient
	 * @param _rowIndex the row index of the target patient
	 * @return returns a cursor to the patient in the database
	 * @throws SQLException throws if nothing found on the specified row index
	 */
	public Cursor getMaxToks(String _cpr) throws SQLException 
	{
		Cursor result = db.query(true, DATABASE_TABLE, new String[] {KEY_ID,  
				KEY_PATIENT_CPR, 
				KEY_MAX_TOKS},
				KEY_PATIENT_CPR + "=" + _cpr, null, null, null, null, null);
		
		if ((result.getCount() == 0) || !result.moveToFirst()) 
		{
			throw new SQLException("No patient found with cpr: " + _cpr);
		}
		
		return result;
	}
	
	/**
	 *  Remove a task based on its index
	 * @param The index of the row to delete.
	 * @return Returns if it succeeded.
	 */
	public boolean removeMaxToks(String cpr) 
	{
		try 
		{
			Cursor c = getMaxToks(cpr);
			long rowIndex = Long.parseLong(c.getString(0));
			
			return db.delete(DATABASE_TABLE, KEY_ID + "=" + rowIndex, null) > 0;
		} 
		catch (Exception e) {
			return false;
		}
	}
	
	/**
	 * Update a patients saved data. If the patient does not exist, it will try to insert the patient (as a new one).
	 * @param _rowIndex The index of the patient to update.
	 * @param the toks value to be updated.
	 * @return If it went well
	 */
	public boolean updateMaxToks(String cpr, Integer toks) 
	{		
		try 
		{
			Cursor c = getMaxToks(cpr);
			long rowIndex = Long.parseLong(c.getString(c.getColumnIndex("_id")));
			
			ContentValues newValue = new ContentValues();
			
			newValue.put(KEY_PATIENT_CPR, cpr);
			newValue.put(KEY_MAX_TOKS, toks);
			
			return db.update(DATABASE_TABLE, newValue, KEY_ID + "=" + rowIndex, null) > 0;
		}
		
		catch (Exception e) 
		{	
			if(insertMaxTosk(cpr, toks) != -1)
				return true;
			else 
				return false; 
		}
	}
	
	private static class DBOpenHelper extends SQLiteOpenHelper {
		public DBOpenHelper(Context context, String name, CursorFactory factory, int version) 
		{
			super(context, name, factory, version);
		}
		
		// SQL Statement to create a new database.
		private static final String DATABASE_CREATE = "create table " +
			DATABASE_TABLE + " (" +
			KEY_ID + " integer primary key autoincrement, " +
			KEY_PATIENT_CPR + " text not null, " +
			KEY_MAX_TOKS + " Integer);";
		
		
		@Override
		public void onCreate(SQLiteDatabase _db) 
		{
			_db.execSQL(DATABASE_CREATE);
		}
		
		@Override
		public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) 
		{
			Log.w("TaskDBAdapter", "Upgrading from version " +
			_oldVersion + " to " +
			_newVersion + ", which will destroy all old data");
			
			// Drop the old table.
			_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
			
			// Create a new one.
			onCreate(_db);
		}
	}
}